<script setup>
defineOptions({ name: 'UserProfile' })
import { ref } from 'vue'
import CardPage from '@/components/CardPage.vue' // 如路径不同请调整
import { userProfileService, userUpdateService } from '@/api/user'
import { ElMessage } from 'element-plus'
import 'element-plus/dist/index.css'
// 表单数据和引用
const formRef = ref(null)
const form = ref({
  id: 0,
  username: '', // 根据截图默认值
  nickname: '',
  email: '',
  user_pic: ''
})
// 表单校验规则
const rules = {
  nickname: [{ required: true, message: '请输入用户昵称', trigger: 'blur' }],
  email: [
    { required: true, message: '请输入用户邮箱', trigger: 'blur' },
    { type: 'email', message: '邮箱格式不正确', trigger: ['blur'] }
  ]
}

// 获取用户资料逻辑
const loading = ref(false)
const getUserProfile = async () => {
  loading.value = true
  const res = await userProfileService()
  const data = res.data
  form.value.nickname = data.nickname
  form.value.email = data.email
  form.value.username = data.username
  form.value.id = data.id
  loading.value = false
}
getUserProfile()
// 提交表单方法
const onSubmit = async () => {
  formRef.value?.validate(async (valid) => {
    if (!valid) return
    const res = await userUpdateService(form.value)
    ElMessage.success(res.message)
  })
}
</script>

<template>
  <card-page title="基本资料">
    <!-- card-page 的默认插槽 -->
    <el-form
      :model="form"
      :rules="rules"
      ref="formRef"
      label-width="100px"
      class="user-form"
      v-loading="loading"
    >
      <el-form-item label="登录名称">
        <el-input v-model="form.username" disabled />
      </el-form-item>

      <el-form-item label="用户昵称" prop="nickname">
        <el-input v-model="form.nickname" placeholder="请输入用户昵称" />
      </el-form-item>

      <el-form-item label="用户邮箱" prop="email">
        <el-input v-model="form.email" placeholder="请输入用户邮箱" />
      </el-form-item>

      <el-form-item>
        <el-button type="primary" @click="onSubmit">提交修改</el-button>
      </el-form-item>
    </el-form>
  </card-page>
</template>

<style scoped lang="scss">
.user-form {
  width: 1500px;
  margin-top: 12px;
  .el-form-item {
    height: 3rem;
    align-items: center;
    .el-form-item__content {
      .el-input {
        height: 2.5rem;
      }
    }
  }
}
</style>
